package com.shiro.receiver.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import com.shiro.receiver.framework.annotation.Interceptor;
import com.shiro.receiver.framework.properties.BotProperties;
import com.shiro.receiver.util.Ed25519Util;

import java.util.List;

@Interceptor
@RequiredArgsConstructor
public class SignatureVerificationInterceptor implements WebInterceptor {

    private final BotProperties botProperties;

    @Override
    public String getName() {
        return "签名验证拦截器";
    }

    @Override
    public Integer getOrder() {
        return 50;
    }

    @Override
    public boolean isEnable() {
        if (botProperties.getInterceptors() == null ||botProperties.getInterceptors().getSignatureVerificationInterceptor().getEnabled() == null) {
            return false;
        }
        return Boolean.TRUE.equals(botProperties.getInterceptors().getSignatureVerificationInterceptor().getEnabled());
    }

    @Override
    public List<String> getPathPatterns() {
        return List.of("/callback");
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        // 获取签名值
        String signature = request.getHeader("X-Signature-Ed25519");
        if (StrUtil.isBlank(signature)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 获取时间戳
        String timestamp = request.getHeader("X-Signature-Timestamp");
        if (StrUtil.isBlank(timestamp)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 合并时间戳和body值
        String message = timestamp + JakartaServletUtil.getBody(request);
        // 校验签名值
        if (!Ed25519Util.verify(botProperties.getConfig().getAppSecret(), message, signature)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

}
